package com.wsm.system.controller;

import com.wsm.common.annotation.OperateLog;
import com.wsm.common.controller.BaseController;
import com.wsm.common.domain.Tree;
import com.wsm.common.service.DictService;
import com.wsm.common.utils.PageUtils;
import com.wsm.common.utils.Query;
import com.wsm.common.utils.Result;
import com.wsm.common.utils.ShiroUtils;
import com.wsm.system.domain.DeptDO;
import com.wsm.system.domain.RoleDO;
import com.wsm.system.domain.UserDO;
import com.wsm.system.service.RoleService;
import com.wsm.system.service.UserService;
import com.wsm.system.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
	private String prefix="system/user"  ;
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	DictService dictService;

	@RequiresPermissions("sys:user:user")
	@GetMapping("")
	String user(Model model) {
		return prefix + "/user";
	}

	@ApiOperation(value = "")
	@GetMapping("/list")
	@ResponseBody
	Result<PageUtils> list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<UserDO> sysUserList = userService.list(query);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(sysUserList, total);
		return Result.success(pageUtil);
	}

	@RequiresPermissions("sys:user:add")
	@OperateLog("添加用户")
	@GetMapping("/add")
	String add(Model model) {
		List<RoleDO> roles = roleService.list();
		model.addAttribute("roles", roles);
		return prefix + "/add";
	}

	@RequiresPermissions("sys:user:edit")
	@OperateLog("编辑用户")
	@GetMapping("/edit/{id}")
	String edit(Model model, @PathVariable("id") Long id) {
		UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);
		return prefix+"/edit";
	}

	@RequiresPermissions("sys:user:add")
	@OperateLog("保存用户")
	@PostMapping("/save")
	@ResponseBody
	Result save(UserDO user) {
		if (userService.save(user) > 0) {
			return Result.success();
		}
		return Result.error();
	}

	@RequiresPermissions("sys:user:edit")
	@OperateLog("更新用户")
	@PostMapping("/update")
	@ResponseBody
	Result update(UserDO user) {
		if (userService.update(user) > 0) {
			return Result.success();
		}
		return Result.deny();
	}


	@RequiresPermissions("sys:user:edit")
	@OperateLog("更新用户")
	@PostMapping("/updatePeronal")
	@ResponseBody
	Result updatePeronal(UserDO user) {
		if (userService.updatePersonal(user) > 0) {
			return Result.success();
		}
		return Result.deny();
	}

	@OperateLog("更新用户个人信息")
	@PostMapping("/onlyUpdatePeronal")
	@ResponseBody
	Result onlyUpdatePeronal(UserDO user) {
		Long userId = ShiroUtils.getUserId();
		if (userId.equals(user.getUserId())) {
			if (userService.updatePersonal(user) > 0) {
				return Result.success();
			}
			return Result.deny();
		} else {
			return Result.denyMsg("用户只能修改个人信息");
		}

	}


	@RequiresPermissions("sys:user:remove")
	@OperateLog("删除用户")
	@PostMapping("/remove")
	@ResponseBody
	Result remove(Long id) {
		if (userService.remove(id) > 0) {
			return Result.success();
		}
		return Result.deny();
	}

	@RequiresPermissions("sys:user:batchRemove")
	@OperateLog("批量删除用户")
	@PostMapping("/batchRemove")
	@ResponseBody
	Result batchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return Result.success();
		}
		return Result.deny();
	}

	@PostMapping("/exit")
	@ResponseBody
	Result<Boolean> exit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return Result.success(!userService.exit(params));
	}

	@RequiresPermissions("sys:user:resetPwd")
	@OperateLog("请求更改用户密码")
	@GetMapping("/resetPwd/{id}")
	String resetPwd(@PathVariable("id") Long userId, Model model) {

		UserDO userDO = new UserDO();
		userDO.setUserId(userId);
		model.addAttribute("user", userDO);
		return prefix + "/reset_pwd";
	}

	@OperateLog("提交更改用户密码")
	@PostMapping("/resetPwd")
	@ResponseBody
	Result resetPwd(UserVO userVO) {
		try {
			userService.resetPwd(userVO, getUser());
			return Result.success();
		} catch (Exception e) {
			return Result.error();
		}

	}

	@RequiresPermissions("sys:user:resetPwd")
	@OperateLog("管理员提交更改用户密码")
	@PostMapping("/adminResetPwd")
	@ResponseBody
	Result adminResetPwd(UserVO userVO) {
		try {
			userService.adminResetPwd(userVO);
			return Result.success();
		} catch (Exception e) {
			return Result.error();
		}

	}

	@GetMapping("/tree")
	@ResponseBody
	public Result<Tree<DeptDO>> tree() {
		Tree<DeptDO> tree = new Tree<DeptDO>();
		tree = userService.getTree();
		return Result.success(tree);
	}

	@GetMapping("/treeView")
	String treeView() {
		return prefix + "/userTree";
	}

	@GetMapping("/personal")
	String personal(Model model) {
		UserDO userDO = userService.get(getUserId());
		model.addAttribute("user", userDO);
		model.addAttribute("sexList", dictService.getSexList());
		return prefix + "/personal";
	}

	@GetMapping("/photo")
	String photo(Model model) {
		return prefix + "/photo";
	}

	@ResponseBody
	@PostMapping("/uploadImg")
	Result uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
		Map<String, Object> result = null;
		try {
			result = userService.updatePersonalImg(file, avatar_data, getUserId());
		} catch (Exception e) {
			return Result.denyMsg("更新图像失败！");
		}
		if (result != null && result.size() > 0) {
			return Result.success(result);
		} else {
			return Result.error("更新图像失败！");
		}
	}
}
